package services
{
	import model.Magazine;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	
	import testdata.MagazinesCollection;

	public class MagazinesManager
	{
		public var magazinesCollection : ArrayCollection;
		
		[Bindable]
		public var selectedMagazine : Magazine;
		
		public function MagazinesManager()
		{
			magazinesCollection = new ArrayCollection();
			var magazines : MagazinesCollection = new MagazinesCollection();
			magazinesCollection.addItem(magazines.magazine1);
			magazinesCollection.addItem(magazines.magazine2);
			magazinesCollection.addItem(magazines.magazine3);
			magazinesCollection.addItem(magazines.magazine4);
			magazinesCollection.addItem(magazines.magazine5);
			magazinesCollection.addItem(magazines.magazine6);
			magazinesCollection.addItem(magazines.magazine7);
			magazinesCollection.addItem(magazines.magazine8);
			magazinesCollection.addItem(magazines.magazine9);
			magazinesCollection.addItem(magazines.magazine10);
			magazinesCollection.addItem(magazines.magazine11);
			selectedMagazine = null;
		}
		
		// search methods
		public function searchBy(searchCriteria:String, searchWord:String, data:ArrayCollection):void
		{
			if(searchCriteria == null || searchCriteria=='' || searchCriteria=='Без филтър')
			{
				data.filterFunction = function(item:Object):Boolean
				{
					return true;
				};
				data.refresh();
			}
			else if(searchCriteria == "Заглавие")
				searchByName(searchWord,data);
			else if(searchCriteria == "Автор")
				searchByPublisher(searchWord, data);
		}
		
		private function searchByName(searchWord:String, data:ArrayCollection):void
		{
			data.filterFunction = function(item:Object):Boolean
			{
				if((item as Magazine).title.toLowerCase() == searchWord.toLowerCase())
					return true;
				return false;
			}
			data.refresh();
			
		}
		
		private function searchByPublisher(searchWord:String, data:ArrayCollection):void
		{
			data.filterFunction = function(item:Object):Boolean
			{
				if((item as Magazine).publisher.toLowerCase() == searchWord.toLowerCase())
					return true;
				return false;
			}
			data.refresh();
		}

		// sorting methods
		public function sort(sortCriteria:String, data:ArrayCollection):void
		{
			if(sortCriteria == "date")
				sortByDate(data);
		}
		
		private function sortByDate(data:ArrayCollection):void
		{
			var s:Sort = new Sort();
			s.fields = [ new SortField("issueDate",false,true,Date) ];
			data.sort = s;
			data.refresh();
			
		}
	}
}